import moment from "moment";
import QRCode from 'qrcodejs2'

export const processServerAPIData = (data: Record<string, any> = {}) => {
  Object.keys(data).forEach((key) => {
    const value = data[key];
    if (Array.isArray(value)) {
      if (!value.length) {
        data[key] = undefined;
      }
    } else if (value === "" || value === null) {
      // 空字符串或 null 转为 undefined
      data[key] = undefined;
    }
  });
};

export const hasChildren = (children: any[]) => {
  return Array.isArray(children) && children.length > 0;
};

export const ParseDate = (
  date: Record<string, any>,
  param = "YYYY-MM-DD HH:mm:ss" || ""
) => {
  if (!date) return "";
  return moment(date).format(param);
};

export const ParseTime = (time: string) => {
  const [hour, minute] = time.split(":");
  const date = new Date();
  date.setHours(Number(hour), Number(minute), 0);
  return date;
};

export const download = (data: any, fileName: any) => {
  const blob = new Blob([data], { type: "application/vnd.ms-excel" });
  // IE
  const navigator: any = window.navigator;
  if (navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(blob, fileName);
  } else {
    const a = document.createElement("a");
    a.href = URL.createObjectURL(blob);
    a.download = fileName;
    a.style.display = "none";
    document.body.appendChild(a);
    a.click();
    URL.revokeObjectURL(a.href);
    document.body.removeChild(a);
  }
};

/**
 * 将参数对象进行格式化转换, 返回格式化后新对象
 * @param ParamsObj 需要格式化的对象, 该对象属性值需为 对象数组
 * @param useKey 以数组元素的哪个 key 作为 新对象的 key , 默认为 "Value"
 * @param useVal 以数组元素的哪个 key 作为 新对象的 val , 默认为 "Title"
 * @returns 格式化后对象 : { xxx : { ... } , yyy : { ... } , ... }
 * @example 
 * const obj = {
        "music": [ 
            { "Title": "酷狗", "Value": "kugou" },
            { "Title": "网易云", "Value": "wangyi" },
             ...
        ],
        ...
    }
    FormatParamsObj(obj)  // { "kugou": "酷狗", "wangyi": "网易云" }
 */
export const ParamsObjFormat = <T extends Record<string, Record<string, any>[]>, K extends keyof T, KT extends keyof T[K][number]>(
  ParamsObj: T,
  useKey: KT = "Value" as KT,
  useVal: KT = "Title" as KT
) => {
  const objArr = Object.entries(ParamsObj)
  const newParamsObj = objArr.reduce((newObj, [key, objVal]) => {

    const newObjVal = objVal.reduce((acc, val) => {
      const accKey = val[useKey as keyof typeof val]
      const value = val[useVal as keyof typeof val]

      if (accKey !== undefined && value !== undefined) {
        acc[accKey] = value;
      }

      return acc
    }, {} as Record<string, string>)
    newObj[key as K] = newObjVal

    return newObj

  }, {} as Record<K, Record<string, string>>)

  return newParamsObj
}

/**
 * 获取指定范围日期
 * @param NMonthAgo 几月前
 * @param NDayAgo 几天前
 * @returns 返回一个包含开始日期和截至日期的对象
 * @property {YYYY-MM-DD} agoYMD - 开始日期
 * @property {YYYY-MM-DD} thisYMD - 截至日期
 */
export const GetRangeDate = (NMonthAgo?: number, NDayAgo?: number) => {
  let date = new Date()
  let m = date.getMonth() + 1
  let d = date.getDate()
  let thisYMD = date.toLocaleDateString().replace(/\//gi, "-")
  date.setMonth(m - 1 - (NMonthAgo ?? 0))
  date.setDate(d - (NDayAgo ?? 0))
  let agoYMD = date.toLocaleDateString().replace(/\//gi, "-")
  return { agoYMD, thisYMD }
}

/**
 * @description 创建谷歌身份验证二维码
 * @param container 二维码容器
 * @param username 用户名
 * @param SystemTitle 管理后台名称
 * @param data 二维码数据
 * @param size 二维码-[宽, 高]
 */
export const CreateBindQrCode = (container: HTMLElement, username: string, SystemTitle: string, data: any, size: [number, number]) => {
  let user = encodeURIComponent(username)
  let title = encodeURIComponent(SystemTitle)
  container.innerHTML = ''

  new QRCode(container, {
    text: `otpauth://totp/${user}?issuer=${title}&secret=${data}`,
    width: size[0],
    height: size[1],
    colorDark: "#333333",
    colorLisght: '#ffffff',
    correctLevel: QRCode.CorrectLevel.H
  })
}

/**
 * @description 获取当前时间对应的提示语
 * @returns 提示语
 */
export const getTimeState = () => {
  let timeNow = new Date();
  let hours = timeNow.getHours();

  if (hours >= 6 && hours <= 10) return `早上好 ⛅`;
  if (hours >= 10 && hours <= 14) return `中午好 🌞`;
  if (hours >= 14 && hours <= 18) return `下午好 🌞`;
  if (hours >= 18 && hours <= 24) return `晚上好 🌛`;
  if (hours >= 0 && hours <= 6) return `凌晨好 🌛`;
}